import { formatMoney } from "accounting-js";
import { toastShort } from "./ToastUtils";

function isEmpty(data) {
  const str = typeof data === "number" ? String(data) : data;
  return str === null || str === "" || str === undefined;
}

function startWith(str, sub) {
  if (typeof str !== "string" || isEmpty(str) || sub.length > str.length) {
    return false;
  }
  if (str.substr(0, sub.length) === sub) {
    return true;
  }
  return false;
}

function trim(str, all = false) {
  return all ? str.replace(/\s+/g, "") : str.replace(/(^\s*)|(\s*$)/g, "");
}

function isEmptyOrSpace(str) {
  if (!isEmpty(str)) {
    str = trim(str);
  }
  return isEmpty(str);
}

function isArrayUseful(arr) {
  return arr !== undefined && arr instanceof Array && arr.length > 0;
}

function fDateShow(date) {
  return formatDate(date, "yyyy年MM月dd日（w） HH:mm");
}

function fDateCommon(date) {
  return formatDate(date, "yyyy-MM-dd HH:mm:ss");
}
/**
 * 将日期格式化成指定格式的字符串
 * @param date 要格式化的日期，不传时默认当前时间，也可以是一个时间戳
 * @param fmt 目标字符串格式，支持的字符有：y,M,d,q,w,H,h,m,S，默认：yyyy-MM-dd HH:mm:ss
 * @returns 返回格式化后的日期字符串
 */

function parseDate(date) {
  const isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s(\d\d):(\d\d):(\d\d)\s*$/;
  let parts;
  try {
    parts = isoExp.exec(date);
  } catch (e) {
    return null;
  }
  if (parts) {
    date = new Date(parts[1], parts[2] - 1, parts[3], parts[4], parts[5], parts[6]);
  } else {
    return null;
  }
  return date;
}

function formatDate(date, fmt) {
  date = date === undefined ? new Date() : date;
  date = typeof date === "number" || typeof date === "string" ? parseDate(date) : date;
  fmt = fmt || "yyyy-MM-dd HH:mm:ss";
  const obj = {
    y: date.getFullYear(), // 年份，注意必须用getFullYear
    M: date.getMonth() + 1, // 月份，注意是从0-11
    d: date.getDate(), // 日期
    q: Math.floor((date.getMonth() + 3) / 3), // 季度
    w: date.getDay(), // 星期，注意是0-6
    H: date.getHours(), // 24小时制
    h: date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 12小时制
    m: date.getMinutes(), // 分钟
    s: date.getSeconds(), // 秒
    S: date.getMilliseconds(), // 毫秒
  };
  const week = ["天", "一", "二", "三", "四", "五", "六"];
  for (var i in obj) {
    fmt = fmt.replace(new RegExp(`${i}+`, "g"), m => {
      let val = `${obj[i]}`;
      if (i == "w") return (m.length > 2 ? "星期" : "周") + week[val];
      for (let j = 0, len = val.length; j < m.length - len; j++) val = `0${val}`;
      return m.length == 1 ? val : val.substring(val.length - m.length);
    });
  }
  return fmt;
}

function moneyFormat(moneyWithPenny, hasSymbol = true) {
  const moneyWithUnitary = moneyWithPenny / 100;
  return formatMoney(moneyWithUnitary, {
    symbol: hasSymbol ? "￥" : "",
    precision: 2,
    thousand: ",",
    decimal: ".",
  });
}

function getRealIdNumber(idCardNo) {
  return idCardNo.replace(/(\w{8})\w{6}(\w+)/, "$1******$2");
}

module.exports = {
  isEmpty,
  isArrayUseful,
  isEmptyOrSpace,
  trim,
  fDateShow,
  fDateCommon,
  startWith,
  moneyFormat,
  getRealIdNumber,
};
